import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.views import View
from django.http import JsonResponse
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from Model.models import PageImg
from radius.models import Radgroupreply as Rad
from tools.Tools import getCurrentUser, createHandleLog

res = dict()
logger_info = logging.getLogger('info')


class pageImgView(View):
    res.clear()

    def get(self, request, *args, **kwargs):
        try:
            dataInfo = PageImg.objects.all()
            data = list(dataInfo.values())
            res['status'] = 200
            res['data'] = data
            res['messages'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def put(self, request, *args, **kwargs):
        try:
            body = json.loads(request.body)
            img = body.get('img')
            num = body.get('num')
            text = body.get('text')
            pageImg = PageImg.objects.get(name_id=num)
            pageImg.img = img
            pageImg.text = text
            pageImg.save()
            res['status'] = 200
            res['message'] = '图文修改成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)
    #
    # @transaction.atomic
    # def delete(self, request, *args, **kwargs):
    #     try:
    #         packageId = request.GET.get("packageId")
    #         delPackage = Package.objects.get(package_id=packageId)
    #         Rad.objects.filter(groupname=packageId).delete()
    #         delPackage.delete()
    #         res['status'] = 200
    #         res['message'] = '套餐删除成功'
    #         createHandleLog('删除套餐', str(getCurrentUser(request)), delPackage.package_name)
    #         logger_info.info(
    #             f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除客户》权限 删除内容 {delPackage.package_name}')
    #         return JsonResponse(res, status=HTTP_200_OK)
    #     except:
    #         logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
    #         res['status'] = 400
    #         res['messages'] = '请求错误'
    #         return JsonResponse(res, status=HTTP_400_BAD_REQUEST)
